/**
 * Copyright (C), 2015-2019, XXX有限公司
 * FileName: LoginController
 * Author:   pc
 * Date:     2019/9/3 17:40
 * Description:
 * History:
 * <author>          <time>          <version>          <desc>
 * 作者姓名           修改时间           版本号              描述
 */
package com.example.rabbitmqdemo.controller;

import com.example.rabbitmqdemo.annotation.MyLog;
import com.example.rabbitmqdemo.service.UserInfoService;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import java.util.Map;

/**
 * 〈功能：〉<br> 
 * 〈登录逻辑控制〉
 * @author liuhaoran
 * @create 2019/9/3 17:40
 * @since 1.0.0
 */
@Controller
@Configuration
@Slf4j
public class LoginController {
	@Autowired
	UserInfoService userInfoService;
	@Autowired
	RedisTemplate redisTemplate;

	@RequestMapping("/gologin")
	public String ftlIndex() {
		System.out.println("login");
		return "login.html";
	}
	@PostMapping("/login")
	@MyLog("登录操作")
	public String login(@RequestParam("userinfoName") String userinfoName,@RequestParam("userinfoPassword")  String userinfoPassword, @RequestParam("verificationCode") String verificationCode, @RequestParam("userinfomail") String userinfomail) {
		ValueOperations<String, Map<String, String>> operations = redisTemplate.opsForValue();
		if(verificationCode == null) {
			return "验证码不能为空";
		} else {
			/**
			 * 加入授权
			 */
			Subject subject = SecurityUtils.getSubject();
			UsernamePasswordToken token = new UsernamePasswordToken(userinfoName, userinfoPassword);
			System.out.println("token:" + token.toString());
			String condeNumber = operations.get(userinfomail+"codenum").get("codenumber").toString();
			if(condeNumber.equals(verificationCode)) {
				try {
					subject.login(token);
					log.info("登录成功");
					return "/admin/index";
				} catch (UnknownAccountException e) {
					log.error("用户名不存在");
					return "用户名不存在";
				} catch (IncorrectCredentialsException e) {
					log.info("密码不正确");
					return "密码不正确";
				}
			} else {
				return "验证码错误请重新获取";
			}
		}
	}
	@ResponseBody
	@RequestMapping("/unAuth")
	public String unAuth() {
		return "未授权";
	}
	@RequestMapping("/goindex")
	public String goindex(){
	 //创建一个视图对象
		return "admin/index";
	}
}